package com.zsc.wxm.ysh.anjo.service.base.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 微服务之间也需要鉴权，服务与服务之间的调用，也需要在请求头里面设置token进行验证
 *
 * @author playmaker
 */
@Configuration
@Slf4j
public class FeignInterceptorConfig implements RequestInterceptor {

    private static final String TOKEN = "Authorization";

    @Override
    public void apply(RequestTemplate requestTemplate) {
        if (getHttpServletRequest() != null) {
            requestTemplate.header(TOKEN, getHeaders(getHttpServletRequest()).get(TOKEN));
        }
    }

    /**
     * 获取httpServletRequest
     *
     * @return HttpServletRequest
     */
    private HttpServletRequest getHttpServletRequest() {
        try {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (servletRequestAttributes != null) {
                return servletRequestAttributes.getRequest();
            }
        } catch (Exception e) {
            log.error("FeignInterceptorConfig发生异常", e);
        }
        return null;
    }

    /**
     * 获取请求头信息
     *
     * @param request 请求对象
     * @return map
     */
    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }


}
